/*******************************************************************************
 Chatty - Mobile Messaging - J2ME ICQ clone
 Copyright (C) 2003-05  Chatty Project

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 ********************************************************************************
 File: src/DrawControls/TextList.java
 Version: ###VERSION###  Date: ###DATE###
 Author(s): Artyomov Denis, Vladimir Kryukov
 *******************************************************************************/


package DrawControls;

import DrawControls.icons.Icon;
import DrawControls.text.*;
import java.util.*;
import javax.microedition.lcdui.*;
import chatty.*;
import chatty.ui.*;
import chatty.ui.base.*;
import chatty.ui.menu.*;
import chatty.util.ResBundle;


/**
 * Text list.
 * 
 * This class store text and data of lines internally.
 * You may use it to show text with colorised lines :)
 */
public class TextList extends VirtualList {
    private Vector pars = new Vector();

    protected Parser createParser(int index) {
        final int width = NativeCanvas.getInstance().getMinScreenMetrics()
                - scrollerWidth - 3;
        return new Parser(index, getFontSet(), width);
    }
    protected void addPar(Parser item) {
        pars.addElement(item.getPar());
    }
    protected Par getPar(int index) {
		return (Par)pars.elementAt(index);
	}

    protected final int getParIndex(int parIndex) {
		if ((getSize() <= parIndex) || (parIndex < 0)) {
            return -1;
        }
		return getPar(parIndex).index;
    }
    
	public final int getSize() {
		return pars.size();
	}

	protected boolean isItemSelected(int index) {
		int selIndex = getCurrItem();
		int textIndex = (selIndex >= getSize()) ? -1 : getPar(selIndex).index;
		if (textIndex == -1) return false;
		return (getPar(index).index == textIndex);
	}

    public void removeFirstText() {
        int size = getSize();
        if (0 < size) {
            int top = Math.max(0, getTopOffset() - getPar(0).getHeight());
            pars.removeElementAt(0);
            // TODO: save cursor position
            setCurrentItem(Math.max(0, getCurrItem() - 1));
            setTopOnPoints(top);
        }
    }

	//! Construct new text list with default values of colors, font size etc...
	public TextList(String capt) {
		super(capt);
		setMenuIcon(Chatty.icons.iconAt(Chatty.ICON_BACK));
        setSoftBarLabels("menu", "back");
	}
	protected int getToolBarIconWidth() {

		return getToolBarIconHeight();
	}
	protected int getToolBarIconHeight() {

		return Math.max(CanvasEx.minItemHeight, Chatty.chatIcons.iconAt(Chatty.ICON_SMILES).getHeight() + 2);
	}
	
	protected int getHeight() {
		if (Options.getBoolean(Options.OPTION_TOOLBAR)) {
			if (NativeCanvas.getInstance().hasPointerEvents() && chatty.Chatty.icons != null)
				return getScreenHeight() - getToolBarIconHeight();
		}
		return getScreenHeight();
    }
	
	// Overrides VirtualList.drawToolBar
	protected final void drawToolBar(GraphicsEx g) {
		if (Chatty.icons == null) return;
			
		int x = 2;
		int y = getHeight();

		int width = getToolBarIconWidth();
		int height = getToolBarIconHeight();

		g.setClip(0, y, getWidth(), height);
		
		int capBkCOlor = g.getThemeColor(CanvasEx.THEME_SOFTBAR_BACKGROUND);
		g.fillGradRect(capBkCOlor, g.transformColorLight(capBkCOlor, -32), 0, y, getWidth(), height);
		g.setColor(g.transformColorLight(capBkCOlor, -128));
		int lineY = (0 == y) ? (height - 1) : y;
		g.drawLine(0, lineY, getWidth(), lineY);
		
			
		int centerX = x + height / 2;
		int centerY = y + height / 2;
		   
		MenuModel 	menu = getMenu();
		int 		count = menu.count();
		
		for (int i = 0; i < count; ++i) {

			centerX = x + height / 2;
			
			g.drawInCenter(menu.getItemIcon(i), centerX, centerY);
			
			x += height;
		}	
	}
	public int getItemHeight(int itemIndex) {
		if (itemIndex >= getSize()) return 1;
		return getPar(itemIndex).getHeight();
	}
	
	// Overrides VirtualList.drawItemData
	protected void drawItemData(GraphicsEx g, int index, int x1, int y1, int w, int h, int skip, int to) {
		getPar(index).paint(getFontSet(), g, 1, y1, skip, to, /*(getCurrItem() == index)*/false);
	}
	protected void stylusTap(int x, int y, boolean longTap) {
	    boolean toolbar = Options.getBoolean(Options.OPTION_TOOLBAR);
	
	    if (y < getCapHeight()) {
		    if (x > getWidth() - menuIcon.getWidth() && toolbar) {
		         back();
		    }
		} else if ( y > getHeight() && toolbar ) {			
			int idx = (x - 2) / getToolBarIconWidth();
			MenuModel menu = getMenu();
			
			menu.exec(null, menu.getItemCodeByIndex(idx) );
		} else
			super.stylusTap(x, y, longTap);
	}
	// Returns text in current selection
	protected final String getCurrText() {
        Par par = getPar(getCurrItem());
        return (null == par) ? null : par.getText();
	}
	protected final String getAllText() {
		StringBuffer result = new StringBuffer();

        // Fills the lines
		int size = getSize();
		for (int i = 0; i < size; ++i) {
			String text = getPar(i).getText();
			if (null != text) {
                result.append(text).append("\n");
            }
		}
		String retval = result.toString().trim();
		return (0 == retval.length()) ? null : retval;
	}

	public int getCurrTextIndex() {
		return getParIndex(getCurrItem());
	}
    protected final void setCurrTextIndex(int textIndex) {
        for (int i = 0; i < getSize(); ++i) {
            if (textIndex == getPar(i).index) {
                setCurrentItem(i);
                return;
            }
        }
        setCurrentItem(0);
        return;
    }

	/** Remove all lines form list */
	public void clear() {
		pars.removeAllElements();
		setCurrentItemIndex(0);
		invalidate();
	}

	public final void setInfoMessage(String text) {
        clear();
        Parser par = createParser(-1);
        par.addText(text, CanvasEx.THEME_TEXT, FONT_STYLE_PLAIN);
        addPar(par);
    }

    protected int backCode = -1;
    protected int defaultCode = -1;
    
    public final void setMenuCodes(int backCode, int defCode) {
        this.backCode = backCode;
        this.defaultCode = defCode;
    }
    protected MenuModel getMenu() {
        return null;
    }

    protected void itemSelected() {
        MenuModel defaultActionMenu = getMenu();
        if ((-1 != defaultCode) && (null != defaultActionMenu)) {
            defaultActionMenu.exec(null, defaultCode);
        }
    }
    protected void doKeyReaction(int keyCode, int actionCode, int type) {
        if (type == KEY_PRESSED) {
            switch (actionCode) {
                case NativeCanvas.LEFT_SOFT:
                    MenuModel menu = getMenu();
                    if (null != menu) {
                        new Select(menu).show();
                    }
                    return;
                    
                case NativeCanvas.RIGHT_SOFT:
                case NativeCanvas.CLOSE_KEY:
                    backAct();
                    return;
            }
        }
        super.doKeyReaction(keyCode, actionCode, type);
    }

    private void backAct() {
        if (backCode == -1) {
            back();
        } else {
            getMenu().exec(null, backCode);
        }
    }    
}